#!/usr/bin/env bash
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

set -e

export BATS_VERSION='1.2.1'

version() {
  printf 'Bats %s\n' "$BATS_VERSION"
}

abort() {
  printf 'Error: %s\n' "$1" >&2
  usage >&2
  exit 1
}

usage() {
  local cmd="${0##*/}"
  local line

  cat <<HELP_TEXT_HEADER
Usage: ${cmd} [OPTIONS] <tests>
       ${cmd} [-h | -v]

HELP_TEXT_HEADER

  cat <<'HELP_TEXT_BODY'
  <tests> is the path to a Bats test file, or the path to a directory
  containing Bats test files (ending with ".bats")

  -c, --count               Count test cases without running any tests
  -f, --filter <regex>      Only run tests that match the regular expression
  -F, --formatter <type>    Switch between formatters: pretty (default),
                              tap (default w/o term), junit
  -h, --help                Display this help message
  -j, --jobs <jobs>         Number of parallel jobs (requires GNU parallel)
  --parallel-preserve-environment
                            Preserve the current environment for "--jobs"
                              (run `parallel --record-env` before)
  --no-tempdir-cleanup      Preserve test output temporary directory
  -o, --output <dir>        Directory to write report files
  -p, --pretty              Shorthand for "--formatter pretty"
  -r, --recursive           Include tests in subdirectories
  -t, --tap                 Shorthand for "--formatter tap"
  -T, --timing              Add timing information to tests
  -v, --version             Display the version number

  For more information, see https://github.com/bats-core/bats-core
HELP_TEXT_BODY
}

expand_path() {
  local path="${1%/}"
  local dirname="${path%/*}"
  local result="$2"

  if [[ "$dirname" == "$path" ]]; then
    dirname="$PWD"
  else
    cd "$dirname"
    dirname="$PWD"
    cd "$OLDPWD"
  fi
  printf -v "$result" '%s/%s' "$dirname" "${path##*/}"
}

BATS_LIBEXEC="$(dirname "$(bats_readlinkf "${BASH_SOURCE[0]}")")"
export BATS_CWD="$PWD"
export BATS_TEST_PATTERN="^[[:blank:]]*@test[[:blank:]]+(.*[^[:blank:]])[[:blank:]]+\{(.*)\$"
export BATS_TEST_FILTER=
export PATH="$BATS_LIBEXEC:$PATH"
export BATS_ROOT_PID=$$
if [[ -z "$TMPDIR" ]]; then
  export BATS_TMPDIR="/tmp"
else
  export BATS_TMPDIR="${TMPDIR%/}"
fi
export BATS_RUN_TMPDIR="$BATS_TMPDIR/bats-run-$BATS_ROOT_PID"

arguments=()

# Unpack single-character options bundled together, e.g. -cr, -pr.
for arg in "$@"; do
  if [[ "$arg" =~ ^-[^-]. ]]; then
    index=1
    while option="${arg:$((index++)):1}"; do
      if [[ -z "$option" ]]; then
        break
      fi
      arguments+=("-$option")
    done
  else
    arguments+=("$arg")
  fi
  shift
done

set -- "${arguments[@]}"
arguments=()

unset flags recursive formatter_flags
flags=()
formatter_flags=()
formatter='tap'
recursive=
tempdir_cleanup=1
output=
if [[ -z "${CI:-}" && -t 0 && -t 1 ]] && command -v tput >/dev/null; then
  formatter='pretty'
fi

while [[ "$#" -ne 0 ]]; do
  case "$1" in
  -h | --help)
    version
    usage
    exit 0
    ;;
  -v | --version)
    version
    exit 0
    ;;
  -c | --count)
    flags+=('-c')
    ;;
  -f | --filter)
    shift
    flags+=('-f' "$1")
    ;;
  -F | --formatter)
    shift
    if [[ $1 =~ ^(pretty|junit|tap)$ ]]; then
      formatter="$1"
    else
      printf "Unknown formatter '%s', valid options are pretty, junit, tap\n" "$1"
      exit 1
    fi
    ;;
  -o | --output)
    shift
    output="$1"
    ;;
  -p | --pretty)
    formatter='pretty'
    ;;
  -j | --jobs)
    shift
    flags+=('-j' "$1")
    ;;
  -r | --recursive)
    recursive=1
    ;;
  -t | --tap)
    formatter='tap'
    ;;
  -T | --timing)
    flags+=('-T')
    formatter_flags+=('-T')
    ;;
  --parallel-preserve-environment)
    flags+=("--parallel-preserve-environment")
    # check if parallel's env setup was run before
    # will print on stderr and return 255 on failure
    # suppress stdout (on success)
    parallel --env _ echo ::: 1 >/dev/null || exit 1
    ;;
  --no-tempdir-cleanup)
    tempdir_cleanup=''
    ;;
  -*)
    abort "Bad command line option '$1'"
    ;;
  *)
    arguments+=("$1")
    ;;
  esac
  shift
done

if [[ -d "$BATS_RUN_TMPDIR" ]]; then
  printf "Error: BATS_RUN_TMPDIR (%s) already exists\n" "$BATS_RUN_TMPDIR" >&2
  printf "Reusing old run directories can lead to unexpected results ... aborting!\n" >&2
  exit 1
fi
mkdir -p "$BATS_RUN_TMPDIR"
if [[ -n "$tempdir_cleanup" ]]; then
  trap 'rm -rf "$BATS_RUN_TMPDIR"' ERR EXIT
fi

if [[ "$formatter" != "tap" ]]; then
  flags+=('-x')
fi
if [[ "$formatter" == "junit" ]]; then
  flags+=('-T')
  formatter_flags+=('-T')
fi

if [[ "${#arguments[@]}" -eq 0 ]]; then
  abort 'Must specify at least one <test>'
fi


if [[ -n "$output" ]]; then
  if [[ ! -w "${output}" ]]; then
    abort "Output path ${output} is not writeable"
  fi
  export BATS_REPORT_OUTPUT_PATH="$output"
fi

filenames=()
for filename in "${arguments[@]}"; do
  expand_path "$filename" 'filename'

  if [[ -d "$filename" ]]; then
    shopt -s nullglob
    if [[ "$recursive" -eq 1 ]]; then
      while IFS= read -r -d $'\0' file; do
        filenames+=("$file")
      done < <(find "$filename" -type f -name '*.bats' -print0 | sort -z)
    else
      for suite_filename in "$filename"/*.bats; do
        filenames+=("$suite_filename")
      done
    fi
    shopt -u nullglob
  else
    filenames+=("$filename")
  fi
done

# shellcheck source=lib/bats-core/validator.bash
source "$BATS_ROOT/lib/bats-core/validator.bash"

set -o pipefail execfail
exec bats-exec-suite "${flags[@]}" "${filenames[@]}" | bats_test_count_validator | "bats-format-${formatter}" "${formatter_flags[@]}"
